<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/28 0028
 * Time: 11:49
 */

namespace app\admin\controller;

use app\common\logic\ModuleLogic;
use think\Db;
use think\Container;
use think\Page;
use Config;
class Admin extends Base
{
    public function index() {
        $list = array();
        $keywords = input('keywords/s');

        //操作
        $action = [
            ['button' => 'a', 'text' => '新增', 'type' => 'add', 'href' => url('admin/admin_info') ,'msg' => ''],
            ['button' => 'button', 'text' => '删除', 'type' => 'delete', 'href' => url('admin/adminHandle'), 'msg' => '确定要删除吗?']
        ];
        if(empty($keywords)){
            $count = M('admin_user')->count();
            $page = new Page($count, Config::get('template.paginate.list_rows'));
            $res = M('admin_user')->order('admin_id desc')->limit($page->firstRow, $page->listRows)->select();
        }else{
            $count = M('admin_user')->where('user_name','like','%'.$keywords.'%')->count();
            $page = new Page($count, Config::get('template.paginate.list_rows'));
            $res = M('admin_user')->where('user_name','like','%'.$keywords.'%')->order('admin_id desc')->limit($page->firstRow, $page->listRows)->select();
        }
        $role = M('admin_role')->column('role_id,role_name');
        if($res && $role){
            foreach ($res as $val){
                $val['role'] =  $role[$val['role_id']];
                $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $list[] = $val;
            }
        }
        //createConfirm();
        $this->assign('keywords', $keywords);
        $this->assign('list',$list);
        $this->assign('page', $page->show());
        $this->assign('action', $action);
        return $this->fetch();
    }

    public function adminHandle(){
        $data = Container::get('request')->param();
        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $salt = rand(1, 9999);
            $data['ec_salt'] = $salt;
            $data['password'] = encrypt($data['password'], $salt);
        }

        if($data['act'] == 'add'){
            unset($data['admin_id']);
            unset($data['act']);
            $data['add_time'] = time();
            if(M('admin_user')->where("user_name", $data['user_name'])->count()){
                $this->error("此用户名已被注册，请更换",url('Admin/Admin/admin_info'));
            }else{
                $r = M('admin_user')->insert($data);
            }
            goto END;
        }

        if($data['act'] == 'edit'){
            unset($data['act']);
            if(M('admin_user')->where("user_name", $data['user_name'])->where("admin_id", "<>", $data['admin_id'])->count()){
                $this->error("此用户名已被注册，请更换");
            }
            $r = M('admin_user')->where('admin_id', $data['admin_id'])->update($data);
            goto END;
        }
        if($data['act'] == 'del'){
            if (is_array($data['ids'])) {
                $admin_id = implode(',', $data['ids']);
            }else {
                $admin_id = $data['ids'];
            }
            $r = M('admin_user')->delete($admin_id);
            $this->success('删除成功');
        }
        END:
        if($r){
            $this->success("操作成功",url('Admin/Admin/index'));
        }else{
            $this->error("操作失败",url('Admin/Admin/index'));
        }
    }
    /**
     * 管理员编辑
     * @param $admin_id
     */
    public function admin_info($admin_id = '') {
        if (empty($admin_id)) {
            $act = 'add';
        }else {
            $act = 'edit';
            $admin_id = intval($admin_id);
            if ($admin_id <= 0) {
                $this->error('参数有误');
            }
            //获取信息
            $info = M('admin_user')->where("admin_id", $admin_id)->find();
            $info['password'] =  "";
            $this->assign('info',$info);
        }
        $this->assign('act',$act);
        $role = M('admin_role')->select();
        $this->assign('role',$role);
        return $this->fetch();
    }
    public function role () {
        $action = [
            ['button' => 'a', 'text' => '新增', 'type' => 'add', 'href' => url('admin/role_info') ,'msg' => '']
        ];

        $list = M('admin_role')->order('role_id desc')->select();
        $this->assign('list',$list);
        $this->assign('action', $action);
        return $this->fetch();
    }
    public function role_info(){
        $role_id = $this->request->param('role_id');
        $detail = array();
        if($role_id){
            $detail = M('admin_role')->where("role_id",$role_id)->find();
            $detail['act_list'] = explode(',', $detail['act_list']);
            $this->assign('detail',$detail);
        }
        $right = M('system_menu')->order('id')->select();
        foreach ($right as $val){
            $val['enable'] = 0;
            if(!empty($detail)){
                $val['enable'] = in_array($val['id'], $detail['act_list']);
            }
            $modules[$val['group']][] = $val;
        }
        //admin权限组
        $group = (new ModuleLogic)->getPrivilege(0);
        $this->assign('group',$group);
        $this->assign('modules',$modules);
        return $this->fetch();
    }

    public function roleSave(){
        $data = $this->request->param();
        $res = $data['data'];
        $res['act_list'] = isset($data['right']) && is_array($data['right']) ? implode(',', $data['right']) : '';
        if(empty($res['act_list']))
            $this->error("请选择权限!");
        if(empty($data['role_id'])){
            $admin_role = Db::name('admin_role')->where(['role_name'=>$res['role_name']])->find();
            if($admin_role){
                $this->error("已存在相同的角色名称!");
            }else{
                $r = M('admin_role')->insert($res);
            }
        }else{
            $admin_role = Db::name('admin_role')->where(['role_name'=>$res['role_name']])->where('role_id','<>', $data['role_id'])->find();
            if($admin_role){
                $this->error("已存在相同的角色名称!");
            }else{
                $r = M('admin_role')->where('role_id', $data['role_id'])->update($res);
            }
        }
        if($r !== false){
            adminLog('管理角色');
            $this->success("操作成功!",url('Admin/Admin/role'));
        }else{
            $this->error("操作失败!",url('Admin/Admin/role'));
        }
    }

    public function roleDel(){
        $role_id = $this->request->param('role_id');
        $admin = M('admin_user')->where('role_id',$role_id)->find();
        if($admin){
            $this->error('请先清空所属该角色的管理员');
        }else{
            $d = M('admin_role')->where("role_id", $role_id)->delete();
            if($d){
                $this->success('删除成功');
            }else{
                $this->error('删除失败');
            }
        }
    }
    public function log(){
        //操作
        $action = [
            ['button' => 'button', 'text' => '删除', 'type' => 'delete', 'href' => url('admin/adminHandle'), 'msg' => '确定要删除吗?']
        ];
        $admin_name = $this->request->param('admin_name');
        $p = $this->request->param('p');
        $where = [];
        if (!empty($admin_name)) {
            $where[] = ['a.user_name', 'like' , '%'.$admin_name.'%'];
        }
        $logs = DB::name('admin_log')
            ->alias('l')
            ->join('__ADMIN_USER__ a','a.admin_id =l.admin_id')
            ->where($where)
            ->order('log_time DESC')
            ->page($p.',20')
            ->select();
        $this->assign('list',$logs);
        $count = DB::name('admin_log')->alias('l')->join('__ADMIN_USER__ a','a.admin_id =l.admin_id')->where($where)->count();
        $Page = new Page($count,20);
        $show = $Page->show();
        $this->assign('pager',$Page);
        $this->assign('page',$show);
        $this->assign('admin_name', $admin_name);
        $this->assign('action', '');
        return $this->fetch();
    }
}